package com.maweirdos.ai.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

/**
 * 聊天控制器
 * 提供聊天接口，使用数据库持久化聊天记忆
 */
@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

    private static final String CHAT_MEMORY_CONVERSATION_ID_KEY = "chatMemoryConversationId";
    private static final String CHAT_MEMORY_RETRIEVE_SIZE_KEY = "chatMemoryRetrieveSize";
    // 在Spring AI 1.0.0.2中，MessageChatMemoryAdvisor没有CLEAR_MEMORY_KEY常量
    private static final String CLEAR_MEMORY_KEY = "clearMemory";

    private final ChatClient chatClient;

    @Autowired
    public ChatController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    /**
     * 聊天接口
     * @param message 用户消息
     * @param chatId 会话ID，如果为空则自动生成
     * @return 聊天响应
     */
    @GetMapping("/message")
    public Map<String, Object> chat(
            @RequestParam String message,
            @RequestParam(required = false) String chatId) {
        
        // 如果没有提供会话ID，则生成一个新的
        final String conversationId;
        if (chatId == null || chatId.isEmpty()) {
            conversationId = UUID.randomUUID().toString();
        } else {
            conversationId = chatId;
        }
        
        log.info("Received chat request with message: {} for chatId: {}", message, conversationId);
        
        // 调用AI模型，传递会话ID和消息
        String response = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .content();
        
        // 返回响应和会话ID
        return Map.of(
                "response", response,
                "chatId", conversationId
        );
    }
    
    /**
     * 清除会话历史
     * @param chatId 会话ID
     * @return 操作结果
     */
    @DeleteMapping("/history/{chatId}")
    public Map<String, Object> clearChatHistory(@PathVariable String chatId) {
        log.info("Clearing chat history for chatId: {}", chatId);
        
        try {
            // 使用自定义参数来清除会话历史
            chatClient.prompt()
                    .user("clear history")
                    .advisors(advisorSpec -> advisorSpec
                            .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                            .param(CLEAR_MEMORY_KEY, true))
                    .call();
            
            return Map.of(
                    "success", true,
                    "message", "Chat history cleared successfully"
            );
        } catch (Exception e) {
            log.error("Error clearing chat history: {}", e.getMessage(), e);
            return Map.of(
                    "success", false,
                    "message", "Failed to clear chat history: " + e.getMessage()
            );
        }
    }
} 